package file

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
)

// func: PathExists(path string) (bool, error)
// aim: 文件目录是否存在

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}


// func: WriteStringWithEnter(dataStr, fp string) error
// aim: 自动换行插入数据，没有文件并且自动创建

func WriteStringWithEnter(dataStr, fp string) error {
	var (
		f   *os.File
		err error
		dir string
		ok bool
	)

	// 自动创建文件目录
	dir = filepath.Dir(fp)
	if ok, _ = PathExists(dir); !ok {
		if err = CreateDir(dir); err != nil {
			return err
		}
	}

	if f, err = os.OpenFile(fp, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660); err != nil {
		return err
	}
	defer func() {
		f.Sync()
		f.Close()
	}()

	if _, err = f.WriteString(dataStr + "\n"); err != nil {
		return err
	}

	return nil
}


// func: ReadFileSplitEnter(filePath string) ([]string, error)
// aim: 读取文件，返回以换行符为分割的切片

func ReadFileSplitEnter(filePath string) ([]string, error) {
	var (
		err  error
		res  []string
		data []byte
		ok bool
	)

	if ok, _ = PathExists(filePath); !ok {
		return nil, errors.New("文件不存在,无法读取")
	}

	res = make([]string, 0)
	if data, err = ioutil.ReadFile(filePath); err != nil {
		return nil, err
	}

	tmp := strings.Split(string(data), "\n")
	for _, v := range tmp {
		if v == "" {
			continue
		}

		res = append(res, v)
	}

	return res, nil
}